<?php

namespace App\Service\Cruise\CruiseProject;

use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\Rms\RmsSysApi;
use App\Models\Cruise\CruiseTemplateModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CruiseBaseService
{
    /**
     * cruise底层配置表，获取id方法
     * @param string $table
     * @return int|null
     */
    public static function popId(Model $model): ?int
    {
        $table = (new $model)->getTable();

        $do = function () use ($table): ?int {
            if (config('app.env') == 'pre' || config('app.env') == 'prod') {
                return null;
            }

            // 线上的最大id
            $prodId = (new RmsSysApi())->getTableMaxId($table)['data']['id'] ?? 0;

            // 当前最大id
            $localId = DB::table($table)->max('id');

            Log::info("CruiseBaseService popId: table:{$table} localId:{$localId} prodId{$prodId}");

            if ($localId <= $prodId) {
                return $prodId + 100;
            }

            if ($localId - 50 <= $prodId) {
                return $prodId + 100;
            }

            // 正常自增场景
            return null;
        };

        $id = $do();
        Log::info("CruiseBaseService popId: table:{$table} id:{$id}");

        return $id;
    }

    const PERMISSION_TO_TYPE_MAPPINGS = [
        'cruise.template.help'    => CruiseTemplateModel::TYPE_1,
        'cruise.template.site'    => CruiseTemplateModel::TYPE_2,
        'cruise.template.check'   => [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_5, CruiseTemplateModel::TYPE_8],
        'cruise.template.college' => CruiseTemplateModel::TYPE_4,
        'cruise.template.tour'    => CruiseTemplateModel::TYPE_6,
        'cruise.template.other'   => CruiseTemplateModel::TYPE_99,
        'cruise.template.workflow'   => CruiseTemplateModel::TYPE_7,
        'cruise.template.activity'   => CruiseTemplateModel::TYPE_9,
    ];

    /**
     * 获取权限对应的稽核types
     * @param array $permissionList
     * @return array
     */
    public static function getPermissionTypes(array $permissionList): array
    {
        $types = [];

        foreach (self::PERMISSION_TO_TYPE_MAPPINGS as $permission => $type) {
            if (in_array($permission, $permissionList)) {

                if (!is_array($type)) {
                    $types[] = $type;
                } else {
                    foreach ($type as $t) {
                        $types[] = $t;
                    }
                }
            }
        }

        return $types;
    }
}
